package com.kxmall.admin.controller.vehicle.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kxmall.common.core.domain.PageQuery;
import com.kxmall.common.core.page.TableDataInfo;
import com.kxmall.common.enums.VehicleStatusType;
import com.kxmall.common.exception.ServiceException;
import com.kxmall.common.helper.LoginHelper;
import org.apache.commons.lang3.StringUtils;
import com.kxmall.vehicle.domain.KxVehicleBoxDownGoods;
import com.kxmall.vehicle.domain.KxVehicleOutGoods;
import com.kxmall.vehicle.domain.KxVehicle;
import com.kxmall.vehicle.domain.bo.KxVehicleBoxOutGoodsBo;
import com.kxmall.vehicle.domain.vo.KxVehicleBoxDownGoodsVo;
import com.kxmall.vehicle.domain.vo.KxVehicleOutGoodsVo;
import com.kxmall.vehicle.domain.vo.KxVehicleVo;
import com.kxmall.vehicle.mapper.KxVehicleBoxDownGoodsMapper;
import com.kxmall.vehicle.mapper.KxVehicleOutGoodsMapper;
import com.kxmall.vehicle.mapper.KxVehicleMapper;
import com.kxmall.admin.controller.vehicle.service.IKxVehicleBoxDownGoodsService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 商品出库Service业务层处理
 */
@RequiredArgsConstructor
@Service
public class KxVehicleBoxDownGoodsServiceImpl implements IKxVehicleBoxDownGoodsService {

    @Autowired
    private KxVehicleMapper vehicleMapper;
    @Autowired
    private KxVehicleOutGoodsMapper vehicleOutGoodsMapper;
    @Autowired
    private KxVehicleBoxDownGoodsMapper vehicleBoxOutGoodsMapper;

    /**
     * 查询商品出库
     */
    @Override
    public KxVehicleBoxDownGoodsVo queryById(Long id) {
        KxVehicleBoxDownGoodsVo kxVehicleBoxDownGoodsVo = vehicleBoxOutGoodsMapper.selectVoById(id);
//        List<KxVehicleOutGoodsVo> outVehicleProductVos = vehicleOutGoodsMapper.selectVoList(
//                new LambdaQueryWrapper<KxVehicleOutGoods>()
//                .eq(KxVehicleOutGoods::getOutVehicleNumbers, kxVehicleBoxDownGoodsVo.getOutVehicleNumbers()));
//        kxVehicleBoxDownGoodsVo.setOutVehicleProductVoList(outVehicleProductVos);
        return kxVehicleBoxDownGoodsVo;
    }

    /**
     * 查询商品出库列表
     */
    @Override
    public TableDataInfo<KxVehicleBoxDownGoodsVo> queryPageList(KxVehicleBoxOutGoodsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<KxVehicleBoxDownGoods> lqw = buildQueryWrapper(bo);
        Page<KxVehicleBoxDownGoodsVo> result = vehicleBoxOutGoodsMapper.selectVoPage(pageQuery.build(), lqw);
        List<KxVehicle> vehicleList = vehicleMapper.selectList();
        result.getRecords().stream()
            .filter(record -> vehicleList.stream().anyMatch(storage -> storage.getId().equals(record.getVehicleId())))
            .forEach(record -> record.setVehicleName(vehicleList.stream()
                .filter(storage -> storage.getId().equals(record.getVehicleId()))
                .findFirst()
                .map(KxVehicle::getVehicleName)
                .orElse(null)));
        return TableDataInfo.build(result);
    }

    /**
     * 查询商品出库列表
     */
    @Override
    public List<KxVehicleBoxDownGoodsVo> queryList(KxVehicleBoxOutGoodsBo bo) {
        LambdaQueryWrapper<KxVehicleBoxDownGoods> lqw = buildQueryWrapper(bo);
        return vehicleBoxOutGoodsMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<KxVehicleBoxDownGoods> buildQueryWrapper(KxVehicleBoxOutGoodsBo bo) {
        LambdaQueryWrapper<KxVehicleBoxDownGoods> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getVehicleId() != null, KxVehicleBoxDownGoods::getVehicleId, bo.getVehicleId());
        //lqw.eq(StringUtils.isNotBlank(bo.getOutVehicleNumbers()), KxVehicleBoxDownGoods::getOutVehicleNumbers, bo.getOutVehicleNumbers());
        //lqw.eq(bo.getStates() != null, KxVehicleBoxDownGoods::getStates, bo.getStates());
        lqw.eq(StringUtils.isNotBlank(bo.getOutPerson()), KxVehicleBoxDownGoods::getDownPerson, bo.getOutPerson());
        lqw.eq(bo.getOutTime() != null, KxVehicleBoxDownGoods::getDownTime, bo.getOutTime());
        lqw.eq(StringUtils.isNotBlank(bo.getRemarks()), KxVehicleBoxDownGoods::getRemarks, bo.getRemarks());
        //lqw.eq(StringUtils.isNotBlank(bo.getOutDay()), KxVehicleBoxDownGoods::getDownDay, bo.getOutDay());
        return lqw;
    }

    /**
     * 新增商品出库
     */
    @Override
    public Boolean insertByBo(KxVehicleBoxOutGoodsBo bo) {
        //自动生成入柜单号,O+年月日+流水号
        //查询数据库最新生成的编号
        KxVehicleBoxDownGoods selectByMax = vehicleBoxOutGoodsMapper.selectByMax();
        String max_code = "";//定义数据库的截取的数据
        String out_skock = "";//定义拼接好的字符串
//        if (selectByMax != null) {
//            max_code = selectByMax.getOutVehicleNumbers();
//        }
        //定义时间字符串拼接
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String uid_pfix = simpleDateFormat.format(new Date());
        //判断数据库是否有数据
        if (max_code != null && max_code.contains(uid_pfix)) {
            String uid_end = max_code.substring(9, 14);
            Integer endNum = Integer.parseInt(uid_end);
            //100001
            endNum = 100000 + endNum + 1;
            String num = endNum + "";
            //去掉100001中的首位1
            String numm = num.substring(1);
            out_skock = "I" + uid_pfix + numm;
        } else {
            //数据库没数据时
            out_skock = "I" + uid_pfix + "00001";
        }
        //入柜商品加入数据库
//        List<KxVehicleOutGoodsVo> productVoList = bo.getOutVehicleProductVoList();
//        if (!CollectionUtils.isEmpty(productVoList)) {
//            for (KxVehicleOutGoodsVo VehicleProductVo : productVoList) {
//                VehicleProductVo.setOutVehicleOrder(out_skock);
//                KxVehicleOutGoods vehicleProduct = BeanUtil.toBean(VehicleProductVo, KxVehicleOutGoods.class);
//                if (vehicleOutGoodsMapper.insert(vehicleProduct) <= 0) {
//                    throw new ServiceException("入柜商品添加失败");
//                }
//            }
//        }
        //入柜添加
        KxVehicleBoxDownGoods goodsUpVehicleBox = BeanUtil.toBean(bo, KxVehicleBoxDownGoods.class);
        //goodsUpVehicleBox.setOutVehicleNumbers(out_skock);
        //goodsUpVehicleBox.setStates(GoodsUpVehicleBoxType.TO_BE_FOR_VEHICLE.getCode());
        goodsUpVehicleBox.setUpdateTime(new Date());
        if (vehicleBoxOutGoodsMapper.insert(goodsUpVehicleBox) <= 0) {
            throw new ServiceException("管理员系统未知异常");
        }
        return true;

    }

    /**
     * 修改商品出库
     */
    @Override
    public Boolean updateByBo(KxVehicleBoxOutGoodsBo bo) {
//        LambdaQueryWrapper<KxVehicleOutGoods> wrapper = new LambdaQueryWrapper<>();
//        wrapper.like(KxVehicleOutGoods::getOutVehicleOrder, bo.getOutVehicleOrder());
//        if (vehicleOutGoodsMapper.delete(wrapper) <= 0) {
//            throw new ServiceException("出库商品更新失败");
//        }
//        //出库商品加入数据库
//        List<KxVehicleOutGoodsVo> VehicleProductVoList = bo.getOutVehicleProductVoList();
//        if (!CollectionUtils.isEmpty(VehicleProductVoList)) {
//            for (KxVehicleOutGoodsVo goodsDownVehicleBoxVo : VehicleProductVoList) {
//                KxVehicleOutGoods vehicleProduct = BeanUtil.toBean(goodsDownVehicleBoxVo, KxVehicleOutGoods.class);
//                if (vehicleOutGoodsMapper.insert(vehicleProduct) <= 0) {
//                    throw new ServiceException("出库商品添加失败");
//                }
//            }
//        }
        KxVehicleBoxDownGoods goodsDownVehicleBox = BeanUtil.toBean(bo, KxVehicleBoxDownGoods.class);
        goodsDownVehicleBox.setUpdateTime(new Date());
        if (vehicleBoxOutGoodsMapper.updateById(goodsDownVehicleBox) > 0) {
            return true;
        }
        throw new ServiceException("管理员系统未知异常");

    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(KxVehicleBoxDownGoods entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除商品出库
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        List<KxVehicleBoxDownGoodsVo> goodsDownVehicleBoxVos = vehicleBoxOutGoodsMapper.selectVoBatchIds(ids);
        //删除入柜信息
        if (vehicleBoxOutGoodsMapper.deleteBatchIds(ids) <= 0) {
            throw new ServiceException("出库商品删除失败");
        }
        for (KxVehicleBoxDownGoodsVo outVehicleVo : goodsDownVehicleBoxVos) {
            //批量删除入柜商品
            LambdaQueryWrapper<KxVehicleOutGoods> wrapper = new LambdaQueryWrapper<>();
            //wrapper.like(KxVehicleOutGoods::getOutVehicleNumbers, outVehicleVo.getOutVehicleNumbers());
            if (vehicleOutGoodsMapper.delete(wrapper) <= 0) {
                throw new ServiceException("出库商品删除失败");
            }
        }
        return true;
    }

    @Override
    public Boolean updateDownVehicleBox(KxVehicleBoxOutGoodsBo bo) {
//        if (ObjectUtils.isEmpty(bo.getVehicleId()) && StringUtils.isEmpty(bo.getOutVehicleOrder())) {
//            throw new ServiceException("参数不能为空");
//        }
//        //根据入柜的商品数量更新餐车的数量
//        LambdaQueryWrapper<KxVehicleOutGoods> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(KxVehicleOutGoods::getOutVehicleOrder, bo.getOutVehicleProductVoList());
//        List<KxVehicleOutGoods> outVehicleProducts = vehicleOutGoodsMapper.selectList(wrapper);
//        Long inVehicleCount;//入柜数量
//        for (KxVehicleOutGoods outVehicleProduct : outVehicleProducts) {
//            inVehicleCount = outVehicleProduct.getOutVehicleCount();
//            Long productAttrId = outVehicleProduct.getProductAttrId();
////            if (vehicleGoodsMapper.updateVehicleGoods(bo.getVehicleId(), productAttrId, inVehicleCount) <= 0) {
////                throw new ServiceException("更新商品库存失败");
////            }
//        }
        //更新入柜状态
        KxVehicleBoxDownGoods kxVehicleBoxDownGoods = new KxVehicleBoxDownGoods();
        //kxVehicleBoxDownGoods.setStates(GoodsUpVehicleBoxType.IN_FOR_VEHICLE.getCode());
        kxVehicleBoxDownGoods.setDownPerson(LoginHelper.getUsername());
        kxVehicleBoxDownGoods.setDownTime(new Date());
        kxVehicleBoxDownGoods.setUpdateTime(new Date());
        LambdaQueryWrapper<KxVehicleBoxDownGoods> wrapper1 = new LambdaQueryWrapper<>();
        //wrapper1.eq(KxVehicleBoxDownGoods::getOutVehicleNumbers, bo.getOutVehicleNumbers());
        if (vehicleBoxOutGoodsMapper.update(kxVehicleBoxDownGoods, wrapper1) <= 0) {
            throw new ServiceException("商品入库失败");
        }
        return true;
    }

    @Override
    public List<KxVehicleVo> vehicleAllName(KxVehicleBoxOutGoodsBo bo) {
//        int state = VehicleStatusType.NOMRAL.getCode();
//        return vehicleMapper.getVehicleBoxAllName(state, bo.getVehicleIds());
        return new ArrayList<>();
    }
}
